package com.liull.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 20:35 2020/9/25
 * @Modified By:
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    /** 用来存放channel 实际上是执行的单线程模型 */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        // if (!channelGroup.contains(channel)) {
        //
        // }
        channelGroup.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + " 发送的消息: " + msg + "\n");
            } else {
                ch.writeAndFlush("我发送的消息: " + msg + "\n");
            }
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[服务器]-" + ctx.channel().remoteAddress() + "已上线\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[服务器]-" + ctx.channel().remoteAddress() + "已下线\n");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 广播
        channelGroup.writeAndFlush("[服务器]-" + channel.remoteAddress() + "加入聊天\n");
        // 先写在执行add（）
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 广播
        channelGroup.writeAndFlush("[服务器]-" + channel.remoteAddress() + "退出聊天\n");
        // channelGroup.remove(channel);
    }

}
